package com.kitty.game.activity.service.other;

import com.kitty.common.utils.SpringUtils;
import com.kitty.common.core.SchedulerManager;
import com.kitty.game.activity.model.product.ActivityType;
import com.kitty.game.activity.service.time.FightActivityHandler;
import com.kitty.game.config.NPC;
import com.kitty.game.enter.TitleInfo;
import com.kitty.game.equip.message.RespNotifyMiscEx;
import com.kitty.game.map.model.GroupMapParam;
import com.kitty.game.mirror.model.FightMirror;
import com.kitty.game.mirror.model.MirrorFightParam;
import com.kitty.game.mirror.model.RoleMirror;
import com.kitty.game.npc.message.RespNpcContent;
import com.kitty.game.npc.model.NpcButton;
import com.kitty.game.role.model.Role;
import com.kitty.game.school.model.SchoolSet;
import com.kitty.game.school.service.SchoolService;
import com.kitty.game.team.message.RespMsg;
import com.kitty.game.utils.Const;
import com.kitty.game.utils.TimeUtil;
import com.kitty.game.zhangmen.RespMasterInfo;
import com.kitty.listener.event.FightEndEvent;
import com.kitty.mina.message.MessagePusher;
import org.springframework.stereotype.Component;

import java.text.MessageFormat;

/**挑战掌门处理类*/
@Component
public class ZhangMenHandler extends FightActivityHandler {
    private static final short ACCEPT_MIN_LEVEL = 45;
    /**更新掌门数据间隔*/
    private static final int UPDATE_ZHANGMEN_INTERVAL = (int) (30 * TimeUtil.ONE_MINUTE);

    private static final String CONTENT = "各位同门只要勤学苦练就能够成为我这样的领袖人物。[【挑战掌门】与掌门一战/"+NpcButton.FIHGT_TO_ZHANGMEN.getKey()+"][我要一睹掌门风采/"+NpcButton.VIEW_ZHANGMEN.getKey()+"][进入证道殿/"+NpcButton.ENTER_ZHENGDAODIAN.getKey()+"][离开/离开]";
    private static final String LEVEL_NOT_ENOUGH = "修道不可急功近利，角色达到" + ACCEPT_MIN_LEVEL + "级后再来找我比试吧！[离开]";
    private static final String LEVEL_LESS_TWENTY = "你比我的等级低20级以上，你确定要挑战我吗？[我就是来挑战你的/"+NpcButton.FIHGT_TO_ZHANGMEN.getKey()+"][开个玩笑而已啦/离开]";
    private static final String IN_TEAM = "掌门挑战只能单挑不接受群殴。[离开]";
    private static final String REMAIN_COUNT_NOT_ENOUGH = "修道不可急功近利，明天再来找我比试吧！[离开]";
    private static final String FIGHT_SELF = "你是否要挑战自我。[以我现在的状态更新掌门信息/"+NpcButton.UPDATE_ZHANGMEN_DATA.getKey()+"][我要打败你实现自我超越/"+NpcButton.BEYOND_ZHANGMEN.getKey()+"][离开]";
    private static final String FIGHT_CONFIRM = "你确定要挑战我吗？[我就是来挑战你的/"+NpcButton.FIHGT_TO_ZHANGMEN.getKey()+"][开个玩笑而已啦/离开]";
    private static final String IN_FIGHT = "这会正忙呢，稍后再和你比试。[离开]";
    private static final String NO_FIGHT_PET = "你还没有准备好参战宠物，这样打败你会说我胜之不武。[离开]";
    private static final String FIGHT_WIN = "恭喜你挑战{0}成功，3分钟内无其他玩家挑战你成功，你将获得掌门称谓！";
    private static final String FIGHT_WIN_FIRST_NUMOR = "[#Y{0}#n]经过激烈角逐，#Y{1}#n成为本门#R新任掌门#n，现告之天下，同喜同贺！本门弟子更应以#Y{1}#n为榜样勤学苦练以名扬天下。";
    private static final String FIGHT_WIN_NUMOR = "[#Y{0}#n]经过激烈角逐，#Y{1}#n力挫上任掌门#Y{2}#n，一时其他弟子无人能敌，为师深感欣慰。现告知天下正式赐予#Y{1}#n本派掌门称谓，同喜同贺！";
    private static final String ZHANGMEN_TITLE = "{0}系掌门";
    private static final String ZHANGMEN_MESSGAE = "大家好，我是新一任{0}";
    private static final String FIHGT_FAIL = "你还是先回去勤加练习再来吧！";
    private static final String UPDATE_INTERVAL_TOO_SHORT = "两次更新时间不能少于30分钟，更新无效。";

    @Override
    public String getNpcContent(Role role, NPC bossNpc) {
        SchoolService schoolService = SpringUtils.getBean(SchoolService.class);
        SchoolSet shoolSet = schoolService.getShoolSet((byte) role.getPolar());
        if (bossNpc.getId() == shoolSet.getZhangmen()) {
            return CONTENT;
        }

        return bossNpc.getContent();
    }

    public void sendNpcContent(Role role, NPC bossNpc, String content) {
        RespNpcContent respNpcContent = SpringUtils.getNpcService().getRespNpcContent(role, bossNpc, content);
        SpringUtils.getNpcService().sendRespNpcContent(role, respNpcContent);
    }

    @Override
    public String getNpcContentNotFight(Role role, NPC bossNpc) {
        /**检测是否在战斗中*/
        if (bossNpc.isInFight()) {
            return IN_FIGHT;
        }

        /**小于可挑战等级*/
        if (role.getLevel() < ACCEPT_MIN_LEVEL) {
            return LEVEL_NOT_ENOUGH;
        }

        /**不可组队*/
        if (teamService.isInTeam(role)) {
            return IN_TEAM;
        }

        /**没有挑战次数时*/
        if (SpringUtils.getActivityService().getRemainCount(role, ActivityType.ZHANG_MEN) <= 0) {
            return REMAIN_COUNT_NOT_ENOUGH;
        }

        /**没有参战宠物*/
        if (SpringUtils.getPetService().getPetById(role.getPetBox().getFightPetId(), role) == null) {
            return NO_FIGHT_PET;
        }

        if (role.getTalk().popChooseParam("fight_zhangmen_confirm") != null) {
            return null;
        }

        FightMirror fightMirror = SpringUtils.getMirrorService().getFightMirror(bossNpc.getId());
        if (fightMirror != null) {
            /**挑战对象是自己时*/
            if (fightMirror.getRoleMirror().getUid() == role.getUid() && role.getTalk().popChooseParam("fight_zhangmen_beyond_confirm") == null) {
                return FIGHT_SELF;
            }

            /**等级比掌门等级减20级还小时*/
            if (role.getLevel() < fightMirror.getRoleMirror().getLevel() - 20 && role.getTalk().popChooseParam("fight_zhangmen_level_confirm") == null) {
                role.getTalk().pushChooseParam("fight_zhangmen_level_confirm", true);
                return LEVEL_LESS_TWENTY;
            }
        }

        role.getTalk().pushChooseParam("fight_zhangmen_confirm", true);
        return FIGHT_CONFIRM;
    }

    @Override
    public void doStartFight(Role role, NPC bossNpc) {
        FightMirror fightMirror = SpringUtils.getMirrorService().getFightMirror(bossNpc.getId());
        if (fightMirror == null) {
            /**没有人挑战掌门成功过，则根据挑战玩家数据生成镜像*/
            fightMirror = SpringUtils.getMirrorService().createFightMirror(bossNpc.getId(), role);
        }
        /**开始挑战时就增加完成次数*/
        SpringUtils.getActivityService().addFinishCount(role, ActivityType.ZHANG_MEN, 1);
        bossNpc.setCreateTime(System.currentTimeMillis());

        MirrorFightParam mirrorFightParam = new MirrorFightParam((byte) getFightType(role), bossNpc.getId(), fightMirror);
        SpringUtils.getMirrorService().startFight(role, mirrorFightParam);
    }



    @Override
    public int getFightType(Role role) {
        return Const.fightType_zhangmen;
    }

    @Override
    public NPC getBossNpc(int npcId) {
        return SpringUtils.getMapService().getNpc(npcId);
    }

    @Override
    public void clearNpcAfterWin(Role role, NPC bossNpc) {

    }

    @Override
    public void doFightWinForSingle(Role role, FightEndEvent fightEndEvent, NPC bossNpc) {
        super.doFightWinForSingle(role, fightEndEvent, bossNpc);

        /**替换掌门数据*/
        FightMirror fightMirror = SpringUtils.getMirrorService().createFightMirror(bossNpc.getId(), role);
        FightMirror oldFightMirror = SpringUtils.getMirrorService().getFightMirror(bossNpc.getId());
        SpringUtils.getMirrorService().addFightMirror(fightMirror);
        fightMirror.getRoleMirror().setTitle(bossNpc.getName());
        fightMirror.getRoleMirror().setMessage(MessageFormat.format(ZHANGMEN_MESSGAE, bossNpc.getName()));
        /**更新npc外观*/
        bossService.broadcastNpcUpdate(new GroupMapParam(role), bossNpc);


        /**挑战自己的时候不需要再发称号*/
        if (oldFightMirror == null || oldFightMirror.getRoleMirror().getUid() != role.getUid()) {
            SchoolSet schoolSet = SpringUtils.getBean(SchoolService.class).getShoolSet((byte) role.getPolar());
            String title = MessageFormat.format(ZHANGMEN_TITLE, schoolSet.getTypeName());
            MessagePusher.pushMessage(role, new RespNotifyMiscEx(MessageFormat.format(FIGHT_WIN, title)));

            Role oldRole = (oldFightMirror !=null ? SpringUtils.getPlayerService().getPlayerBy(oldFightMirror.getRoleMirror().getUid()) : null);
            /**旧的掌门称号马上收回*/
            delOldTitle(oldRole, title);
            sendNumor(role, schoolSet, oldRole);
            /**新的掌门称号3分钟后发*/
            addTitle(role, bossNpc, title);
        }
    }

    /**发谣言*/
    private void sendNumor(Role role, SchoolSet schoolSet, Role oldRole) {
        String msg = null;
        String masterName = SpringUtils.getMapService().getNpc(schoolSet.getMaster()).getName();
        if (oldRole == null) {
            msg = MessageFormat.format(FIGHT_WIN_FIRST_NUMOR, masterName, role.getName());
        } else {
            msg = MessageFormat.format(FIGHT_WIN_NUMOR, masterName, role.getName(), oldRole.getName());
        }
        /**发谣言*/
        SpringUtils.getChatService().sendNumor(msg, Const.BRODCAST_MSG_TYPE_ROLE);
    }


    /**收回旧掌门称号*/
    private void delOldTitle(Role role, String title) {
        if (role == null) {return ;}
        SpringUtils.getRoleService().delTitle(role, title);
    }

    /**添加称号*/
    private void addTitle(Role role, NPC bossNpc, String title) {
        /**3分钟后发称号*/
        SchedulerManager.getInstance().schedule(() -> {
            FightMirror newFightMirror = SpringUtils.getMirrorService().getFightMirror(bossNpc.getId());
            if (newFightMirror != null && newFightMirror.getRoleMirror().getUid() == role.getUid()) {
                /**发称号*/
                SpringUtils.getRoleService().addTitle(role, new TitleInfo(title, title));
            }
        }, 3* TimeUtil.ONE_MINUTE);
    }

    @Override
    public void giveReward(Role role, FightEndEvent fightEndEvent, NPC bossNpc) {

    }

    @Override
    public void clearNpcTimeOut(NPC npc) {

    }

    @Override
    public void doFightFail(Role role, FightEndEvent fightEndEvent) {
        super.doFightFail(role, fightEndEvent);
        MessagePusher.pushMessage(role, new RespMsg(FIHGT_FAIL));
    }

    /**更新掌门*/
    public void updateZhangMenData(Role role, NPC bossNpc) {
        FightMirror fightMirror = SpringUtils.getMirrorService().getFightMirror(bossNpc.getId());
        if (fightMirror == null) {return ;}

        /**现在掌门数据不是该玩家的数据，返回*/
        if (fightMirror.getRoleMirror().getUid() != role.getUid()) {return ;}

        /**更新时间间隔不能少于30分钟*/
        if (System.currentTimeMillis() - fightMirror.getCreateTime() < UPDATE_ZHANGMEN_INTERVAL) {
            MessagePusher.pushMessage(role, new RespNotifyMiscEx(UPDATE_INTERVAL_TOO_SHORT));
            return ;
        }

        FightMirror newFightMirror = SpringUtils.getMirrorService().createFightMirror(bossNpc.getId(), role);
        fightMirror.getRoleMirror().setTitle(bossNpc.getName());
        fightMirror.getRoleMirror().setMessage(MessageFormat.format(ZHANGMEN_MESSGAE, bossNpc.getName()));
        SpringUtils.getMirrorService().updateFightMirror(newFightMirror);
    }

    /**超越自己*/
    public void beyondSelf(Role role, NPC bossNpc) {
        role.getTalk().pushChooseParam("fight_zhangmen_beyond_confirm", true);
        startFight(role, bossNpc);
    }

    /**查看掌门信息*/
    public void viewZhangMen(Role role, NPC npc) {
        FightMirror fightMirror = SpringUtils.getMirrorService().getFightMirror(npc.getId());

        RespMasterInfo respMasterInfo = null;
        if (fightMirror == null) {
            /**没有掌门数据*/
            RoleMirror roleMirror = new RoleMirror();
            roleMirror.setIcon(npc.getIcon());
            roleMirror.setName(npc.getName());
            roleMirror.setTitle(npc.getName());
            roleMirror.setLevel(ACCEPT_MIN_LEVEL);
            roleMirror.setMessage(MessageFormat.format(ZHANGMEN_MESSGAE, npc.getName()));
            respMasterInfo = new RespMasterInfo(role, roleMirror);
        } else {
            /**有掌门数据*/
            respMasterInfo = new RespMasterInfo(role, fightMirror.getRoleMirror());
        }

        MessagePusher.pushMessage(role, respMasterInfo);
    }
}
